package com.ygg.controller.api;

import com.alibaba.fastjson.JSONObject;
import com.ygg.helper.JwtHelper;
import com.ygg.model.user.UserInfo;
import com.ygg.result.Result;
import com.ygg.service.UserInfoService;
import com.ygg.utils.ConstantWxPropertiesUtils;
import com.ygg.utils.HttpClientUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/api/ucenter/wx")
public class UserWxApiController {


    @Resource
    private UserInfoService userInfoService;

    /**
     * 获取微信二维码
     *
     * @param session
     * @return
     */
    @GetMapping("getLoginParam")
    @ResponseBody
    public Result genQrConnect(HttpSession session) {
        String redirectUri = null;

        // redirectUri = URLEncoder.encode(ConstantWxPropertiesUtils.WX_OPEN_REDIRECT_URL, "UTF-8");
        Map<String, Object> map = new HashMap<>();
        map.put("appid", ConstantWxPropertiesUtils.WX_OPEN_APP_ID);
        map.put("redirectUri", ConstantWxPropertiesUtils.WX_OPEN_REDIRECT_URL);
        map.put("scope", "snsapi_login");
        map.put("state", System.currentTimeMillis() + "");//System.currentTimeMillis()+""
        return Result.ok(map);

    }

    /**
     * 微信扫码回调路径
     *
     * @param code
     * @param state
     * @return
     */
    @GetMapping("/callback")
    public String callback(String code, String state) {
        //使用code和appid以及appscrect换取access_token
        StringBuffer baseAccessTokenUrl = new StringBuffer()
                .append("https://api.weixin.qq.com/sns/oauth2/access_token")
                .append("?appid=%s")
                .append("&secret=%s")
                .append("&code=%s")
                .append("&grant_type=authorization_code");

        String accessTokenUrl = String.format(baseAccessTokenUrl.toString(),
                ConstantWxPropertiesUtils.WX_OPEN_APP_ID,
                ConstantWxPropertiesUtils.WX_OPEN_APP_SECRET,
                code);
        try {
            //通过code获取access_token的接口。
            String tokenJson = HttpClientUtils.get(accessTokenUrl);
            JSONObject jsonObject = JSONObject.parseObject(tokenJson);
            String accessToken = jsonObject.getString("access_token");
            String openid = jsonObject.getString("openid");

            //根据openid判断用户是否已经注册过
            UserInfo userInfo = userInfoService.query().eq("openid", openid).one();
            //未注册 先注册
            if (userInfo == null) {
                //用accessToken和openid去获取用户信息
                //https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID

                String baseAccessTokenUrl1 = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                String accessTokenUrl1 = String.format(baseAccessTokenUrl1,
                        accessToken, openid, code);

                String UserJson = HttpClientUtils.get(accessTokenUrl1);
                JSONObject userJsonObject = JSONObject.parseObject(UserJson);
                //获取用户昵称
                String nickname = userJsonObject.getString("nickname");
                //获取用户头像路径
                String headimgurl = userJsonObject.getString("headimgurl");

                userInfo = new UserInfo();
                userInfo.setNickName(nickname);
                userInfo.setStatus(1);
                userInfo.setOpenid(openid);
                userInfoService.save(userInfo);
            }

            //返回name 和token
            Map<String, Object> map = new HashMap<>();
            String name = userInfo.getName();
            if (StringUtils.isEmpty(name)) {
                name = userInfo.getNickName();
            }
            if (StringUtils.isEmpty(name)) {
                name = userInfo.getPhone();
            }
            map.put("name", name);
            if (StringUtils.isEmpty(userInfo.getPhone())) {
                map.put("openid", userInfo.getOpenid());
            } else {
                map.put("openid", "");
            }
            String token = JwtHelper.createToken(userInfo.getId(), name);
            map.put("token", token);
            return "redirect:" + ConstantWxPropertiesUtils.YYGH_BASE_URL
                    +"/weixin/callback?token="+map.get("token")
                    +"&openid="+map.get("openid")
                    +"&name="+URLEncoder.encode((String)map.get("name"));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }


    }


}



